<template>
  <div>
    <el-card class="mb-10">
      <CategorySelect :disabled="isEdit"></CategorySelect>
    </el-card>
    <el-card>
      <div v-if="!isEdit">
        <el-button class="mb-10" type="primary" :icon="Plus" :disabled="!categoryStore.category3Id" @click="isEdit = true">添加属性</el-button>
        
        <el-table :data="attrList" border>
          <el-table-column type="index" label="序号" align="center" width="80"></el-table-column>
          <el-table-column label="属性名" width="160" prop="attrName"></el-table-column>
          <el-table-column label="属性值列表">
            <template #default="{ row, $index }">
              <el-tag
                class="mr-5"
                type="success"
                v-for="attrVal in row.attrValueList"
                :key="attrVal.id"
              >{{ attrVal.valueName }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="140">
            <template #default="{ row, $index }">
              <el-button type="warning" size="small" :icon="Edit" @click="editAttr(row)"></el-button>
              <el-popconfirm :title="`确认要删除[${ row.attrName }]吗?`" @confirm="deleteAttr(row)">
                <template #reference>
                  <el-button type="danger"  size="small" :icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div v-else>
        <el-form inline>
          <el-form-item label="属性名">
            <el-input placeholder="输入属性名" v-model="attrForm.attrName"></el-input>
          </el-form-item>
        </el-form>
        <div class="btn mb-10">
          <el-button type="primary" :disabled="!attrForm.attrName" @click="addAttrValue">添加属性值</el-button>
          <el-button @click="onCancel">取消</el-button>
        </div>
        <el-table :data="attrForm.attrValueList" border class="mb-10">
          <el-table-column type="index" label="序号" width="80" align="center"></el-table-column>
          <el-table-column label="属性值名称">
            <template #default="{ row, $index }">

              <el-input
                v-if="row.inputVisible"
                v-model="row.valueName"
                ref="inputRef"
                @blur="inputBlur(row, $index)"
              ></el-input>
              <div v-else @click="showInput(row)">{{ row.valueName }}</div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="80">
            <template #default="{ row, $index }">
              <el-popconfirm :title="`确认要删除[${ row.valueName }]吗?`" @confirm="deleteAttrVal($index)">
                <template #reference>
                  <el-button type="danger" size="small" :icon="Delete"></el-button>
                </template>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <div class="btn">
          <el-button type="primary" :disabled="!(attrForm.attrName && attrForm.attrValueList.length)" @click="onSavew">保存</el-button>
          <el-button @click="onCancel">取消</el-button>
        </div>
      </div>
    </el-card>
  </div>
</template>
<script setup lang="ts">
import { Plus, Edit, Delete } from '@element-plus/icons-vue';
import { ref, watch, nextTick } from 'vue';
import attrApi, {type attrListModel,type AttrValueModel } from '@/api/attr'
import useCategoryStore from '@/stores/category';
import { ElMessage } from 'element-plus';
import { cloneDeep } from 'lodash'
import category from '@/api/category';
const categoryStore = useCategoryStore();
const isEdit = ref(false) // 是否是编辑状态
// 编辑
const editAttr = (row: attrListModel) => {
  isEdit.value = true; // 切换编辑界面
  attrForm.value = cloneDeep(row); // 回显数据
}
// 删除
const deleteAttr = async (row: attrListModel) => {
  try {
    await attrApi.deleteAttr(row.id as number)
    ElMessage.success('删除成功')
    getData() // 重新获取数据刷新界面
  } catch (error) {
    console.error(error)
    ElMessage.error('删除失败,请重试')
  }
}
// 新增收集数据
const initAttrForm = () => ({
  attrName: '',
  attrValueList: [],
  categoryId: undefined, // 在保存的时候去赋值
  categoryLevel: 3 // 写死,新增给第三级分类新增
})
const attrForm = ref<attrListModel>(initAttrForm())
// 新增保存
const onSavew = async () => {
  // 组装数据 - 缺少categoryId数据,进行组装
  attrForm.value.categoryId = categoryStore.category3Id
  // 发送请求
  try {
    await attrApi.saveAttrInfo(attrForm.value)
    ElMessage.success('保存成功') // 提示用户
    isEdit.value = false // 切换主列表界面
    attrForm.value = initAttrForm(); // 清空form表单
    getData() // 重新获取数据刷新页面
  } catch (error) {
    console.error(error)
    ElMessage.error('保存失败,请重试')    
  }
}
const onCancel = () => {
  isEdit.value = false // 切换主列表界面
  attrForm.value = initAttrForm(); // 清空form表单
}
const inputRef = ref<HTMLInputElement>()
// 展示input
const showInput = (row: AttrValueModel) => {
  row.inputVisible = true // 切换input显示,异步更新DOM
  nextTick(() => {
    inputRef.value?.focus()
  })
}
// input失焦
const inputBlur = (row: AttrValueModel, index: number) => {
  // 看下当前用户有没有输入值,没有把当前这条数据干掉
  // 不能为空的校验
  if (!row.valueName) {
    attrForm.value.attrValueList.splice(index, 1)
    return
  }
  // 重复校验
  const isRepeat = attrForm.value.attrValueList.some((item: AttrValueModel, idx: number) => {
    if (index == idx) { // 证明是自己,自己和自己不用比
      return false
    }
    return item.valueName == row.valueName
  })
  if (isRepeat) {
    attrForm.value.attrValueList.splice(index, 1)
    ElMessage.error('输入的内容重复,请重试')
    return
  }
  row.inputVisible = false
}
// 添加平台属性值
const addAttrValue = () => {
  attrForm.value.attrValueList.push({
    valueName: '', // 应该是用户输入的
    inputVisible: true // 用来控制input和div的切换显示
  })

  // inputVisible设置为true,要展示input,此时要更新DOM,更新DOM是异步的,执行代码比更新DOM快,所以获取不到组件实例
  // 此时使用 nextTick 等待DOM更新完毕之后,就可以获取到组件实例了
  nextTick(() => {
    inputRef.value?.focus()
  })
}
// 删除平台属性
const deleteAttrVal = (index: number) => {
  attrForm.value.attrValueList.splice(index, 1)
}





// 获取列表数据
const attrList = ref<attrListModel[]>([])
const getData = async () => {
  const { category1Id, category2Id, category3Id } = categoryStore;
  try {
    let result = await attrApi.getAttrInfoList(category1Id as number, category2Id as number, category3Id as number)
    attrList.value = result;
  } catch (error) {
    ElMessage.error('获取平台属性列表失败,请重试')
  }
}

// 监听三级分类数据
watch(() => categoryStore.category3Id, (nval, oval) => {
  if (nval) { // 获取数据
    getData()
  } else { // 清空数据
    attrList.value = []
  }
}, { immediate: true })

</script>

<style scoped>

</style>